import axios from 'axios';
// import { ElMessageBox, ElMessage } from 'element-plus'
import { ElMessage } from 'element-plus';

import { getToken, clearStorage } from '@/utils/auth';
import router from '@/router';

// create an axios instance
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_API : process.env.VUE_APP_BASE_API + '/apicx', // url = base url + request url

  // baseURL: process.env.VUE_APP_BASE_API + '/api1', // proxy 开起了前端代理
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
  headers: {
    isToken: false //默认不需要token
  }
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    // 是否需要设置 token
    // debugger
    const isToken = (config.headers || {}).isToken === false;
    if (getToken('ust') && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + getToken('ust'); // 让每个请求携带自定义token 请根据实际情况自行修改
    }

    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    // console.log('response', response);
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      });

      // 50008: Illegal token (非法token); 50012: Other clients logged in; 50014: Token expired(token 过期);
      if (res.code === 401) {
        // to re-login
        // ElMessageBox.confirm('请重新登录，身份过期！', {
        //   confirmButtonText: '重登',
        //   cancelButtonText: '取消',
        //   type: 'warning',
        // }).then(() => {
        //   router.push('/logon')
        // })
        clearStorage();
        router.push('/logon');
      }
      return Promise.reject(new Error(res.msg || 'Error'));
    } else {
      return res;
    }
  },
  (error) => {
    console.log('err000' + error); // for debug
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });

    return Promise.reject(error);
  }
);

export default service;
